/*jslint vars: true, forin: true, sloppy: true */
/*global probe, angular, console */
probe.controller("DictionaryEditor", function ($scope, $element, ocDialog, $interval,
												ocAPI, $filter) {
	var DI = ocDialog.queryDI($element);
	$scope.refresh = {
		grid: false
	};
	$scope.state = {
		hasChange: false
	};
	$scope.dictionary = {
		dictionaryId: undefined,
		name: undefined,
		field: [],
		assignment: [[]]
	};
	$scope.editorControl = {};
	$scope.$watch('dictionary.field.length', function () {
		$scope.editorControl.$tabs[1].isDisabled
			= !$scope.dictionary.field.length;
	});
	$scope.fieldCtrl = {
		header: [
			{key: 'name',		width: 100,	text: '字段名'},
			{key: 'pattern',	width: 280,	text: '正则模式'},
			{key: 'comment',	width: 140,	text: '注释'}
		],
		visitFn: function (index) {
			$scope.field = angular.copy(this[index]);
		}
	};
	$scope.assignmentCtrl = {
		header: []
	};

	$scope.menu = [
		{
			title: '文件(F)',
			menu: [
				{
					title: '新建(N)',
					attr: 'ng-click="newDictionary()"'
				},
				{
					title: '打开(O)',
					attr: 'ng-click="openDictionary()"'
				},
				{
					title: '从CSV导入 [beta!]',
					attr: 'oc-dialog-open="importCSV"'
				},
				null,
				{
					title: '保存(S)'
				},
				{
					title: '另存为',
					attr: 'ng-click="saveAsDictionary()"'
				},
				null,
				{
					title: '退出(X)',
					attr: 'oc-dialog-close'
				}
			]
		},
		{
			title: '编辑(E)',
			menu: [
				{
					title: '清空字典',
					attr: 'oc-alert-open="trashDictionary"'
				},
				null,
				{
					title: '预览',
					attr: ' oc-dialog-open="preview"'
				}
			]
		}
	];

	// 新建字典
	$scope.newDictionary = function () {
		var clearDict = function () {
			$scope.dictionary = {
				field: [],
				assignment: [[]]
			};
			$scope.state.hasChange = false;
		};

		if ($scope.state.hasChange) {
			ocDialog.alert({
				title: '尚未保存',
				message: '您的修改尚未保存，新建会导致未保存的编辑丢失。\n确定要放弃当前的编辑结果吗？',
				callFn: clearDict
			}, DI);
		} else {
			clearDict();
		}
	};

	function saveDictionaryExceptionHandle(err) {
		//this = DI of ocFile window
		//todo alert the user
		ocDialog.alert({
			title: '获取失败',
			message: '获取数据字典列表时出错，原因：\n' + err
		}, DI);
		console.error("保存失败", err);
	}
	function listDictionary(actionName, actionFn) {
		ocAPI.use("listDictionary").by().then(function (data) {
			ocDialog.file({
				action: actionName,
				title: '数据字典',
				share: function () {
					return data.dictionaries;
				},
				mapUpdatetime: 'updatetime',
				actionFn: actionFn
			}, DI);
		}, function (err) {
			ocDialog.alert({
				title: '获取失败',
				message: '获取数据字典列表时出错，原因：\n' + err
			}, DI);
		});
	}
	$scope.saveDictionary = function () {
		var d = $scope.dictionary;
		if (d.dictionaryId) {
			ocAPI.use("updateDictionary").by(d.dictionaryId, {
				field: angular.toJson(d.field),
				assignment: angular.toJson(d.assignment)
			})['catch'](saveDictionaryExceptionHandle);
		} else {
			$scope.saveAsDictionary('保存');
		}
	};
	function createDictionary(dictionaries, index, fileName) {
		//this = DI of ocFile window
		var body = {
			"name": fileName,
			comment: '',
			field: angular.toJson($scope.dictionary.field),
			assignment: angular.toJson($scope.dictionary.assignment)
		}, DI = this;

		//创建一个数据字典
		ocAPI.use("createDictionary").by(body).then(function () {
			DI.closeDialog();
		}, saveDictionaryExceptionHandle);
	}
	$scope.saveAsDictionary = function (alias) {
		listDictionary(alias || '另存为', createDictionary);
	};
	function openDictionary(dictionarys, selected) {
		var dictionaryId = dictionarys[selected].dictionaryId;
		ocAPI.use('retrieveDictionary').by(dictionaryId)
			.then(function (data) {
				$scope.dictionary =
					$filter('getDictionary')(data.dictionary);
				//reset header
				var head = $scope.assignmentCtrl.header;
				head.length = 0;
				angular.forEach($scope.dictionary.field, function (field) {
					head.push({
						text: field.name,
						width: 120
					});
				});
				$scope.refresh.grid = !$scope.refresh.grid;
				DI.$$scope.title =
					data.dictionary.name + ' - 数据字典编辑器';
			});
		this.closeDialog();
		$scope.state.hasChange = false;
	}
	$scope.openDictionary = function () {
		listDictionary('打开', openDictionary);
	};

	$scope.importCSV = {
		name: 'dictionary/import',
		share: function () {
			return {
				data: $scope.dictionary,
				head: $scope.assignmentCtrl.header,
				refresh: function () {
					$scope.refresh.grid = !$scope.refresh.grid;
				}
			};
		}
	};
	$scope.deleteField = function () {
		var fieldCtrl = $scope.fieldCtrl;

		$scope.dictionary.field.splice(fieldCtrl.selected, 1);
		$scope.assignmentCtrl.header.splice(fieldCtrl.selected, 1);
		angular.forEach($scope.dictionary.assignment, function (row) {
			row.splice(fieldCtrl.selected, 1);
		});

		if (!$scope.assignmentCtrl.header.length) {
			$scope.trashDictionary.callFn();
		}
	};
	$scope.trashDictionary = {
		title: "清空字典",
		message: "您确定要放弃当前的编辑结果清空字典吗？",
		callFn: function () {
			$scope.assignmentCtrl.header = [];
			$scope.dictionary.field = [];
			$scope.dictionary.assignment = [[]];
			$scope.editorControl.selected = 0;
		}
	};
	$scope.deleteAssignment = function () {
		$scope.dictionary.assignment.push([]);
	};
	$scope.addAssignment = function () {
		$scope.dictionary.assignment.push([]);
	};
	$scope.preview = {
		name: 'dictionary/preview',
		share: function () {
			return $scope.dictionary;
		}
	};

	// 自动增加特殊值
	$interval(function () {
		if (!$scope.dictionary || !$scope.dictionary.field.length) {
			return;
		}

		var last, isAnyDefined = false,
			assign = $scope.dictionary.assignment;

		if (!assign.length) {
			assign.push([]);
			return;
		}

		last = assign[assign.length - 1];

		angular.forEach(last, function (cell) {
			isAnyDefined = isAnyDefined || cell;
		});

		if (isAnyDefined) {
			$scope.addAssignment();
		}
	}, 500);

	$scope.field = {
		name: '',
		pattern: '',
		comment: ''
	};
	$scope.appendNewField = function () {
		$scope.dictionary.field.push($scope.field);
		$scope.assignmentCtrl.header.push({
			text: $scope.field.name,
			width: 120
		});
		$scope.field = {
			name: '',
			pattern: '',
			comment: ''
		};
		$scope.state.hasChange = true;
	};

	$scope.preinstall = [
		{
			pattern: "\\d{10}",
			comment: "十位随机数字"
		},
		{
			pattern: "\\w{5,16}@qq\\.com",
			comment: "qq邮箱"
		},
		{
			pattern: "[0-9a-f]{16}",
			comment: "16位小写MD5"
		},
		{
			pattern: "[0-9A-F]{16}",
			comment: "16位大写MD5"
		}
	];

	$scope.listCtrl = {
		header: [
			{
				key: "pattern",
				text: "正则模式",
				width: 120
			},
			{
				key: "comment",
				text: "注释",
				width: 160
			}
		],
		visitFn: function (index) {
			angular.extend($scope.field, $scope.preinstall[index]);
		}
	};
});
